package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author lqw
 * @since 2022-06-20
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {
    /**
     * 新增自媒体用户
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        this.save(wmUser);
        return ResponseResult.okResult(wmUser);
    }

    /**
     * 修改自媒体用户
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult updateWmUser(WmUser wmUser) {
        this.updateById(wmUser);
        return ResponseResult.okResult();
    }

    /**
     * 自媒体账户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
    //判断用户名和密码是否为空
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getName,dto.getName());
        WmUser wmUser = this.getOne(query);
        //不存在提示用户不存在
        if (StringUtils.isEmpty(wmUser)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在的话,取出用户数据中的盐
        String salt = wmUser.getSalt();
        //将用户传来的密码和数据库中的盐相加  进行MD5加密
        String pwd = dto.getPassword()+salt;
        String md5Pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        //对比数据库中储存的密码
        if (!wmUser.getPassword().equals(md5Pwd)){
            //密码不正确
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码正确
        //生成token
        Map<String,Object> info = new HashMap<>();
        info.put("userId" , wmUser.getId());
        String token = AppJwtUtil.getToken(info);
        //给前端返回token
        WmUser user = new WmUser();
        user.setName(wmUser.getName());
        Map<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
